package com.black.utils.office.excel;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import org.apache.commons.compress.utils.Lists;

import java.util.List;
import java.util.Objects;

/**
 * @author ylx
 */
@Data
public class ExcelHeader {
    private String name;
    private String key;
    private int row;
    private int lastRow;
    private int column;
    private int lastColumn;
    private int colspan;
    private int rowspan;
    private int depth;
    private int columnWidth;
    private List<ExcelHeader> children;

    public ExcelHeader(String name) {
        this(name, null);
    }

    public ExcelHeader(String name, String key) {
        if (name == null) {
            throw new IllegalArgumentException("Excel header name can not be null");
        }
        this.name = name;
        this.key = key;
        this.columnWidth = name.length() << 9;
    }

    public ExcelHeader(String name, String key, int columnWidth) {
        this.name = name;
        this.key = key;
        this.columnWidth = columnWidth;
    }

    public void addChild(ExcelHeader child) {
        if (children == null) {
            children = Lists.newArrayList();
        }
        children.add(child);
    }

    public void deepSort() {
        if (this.children != null) {
            this.children.sort(null);
            for (ExcelHeader child : this.children) {
                child.deepSort();
            }
        }
    }

    public static ExcelHeader fromJson(String json) {
        return JSONObject.parseObject(json, ExcelHeader.class);
    }

    public static List<ExcelHeader> fromJsonArray(String json) {
        List<ExcelHeader> headers = JSONArray.parseArray(json, ExcelHeader.class);
        headers.sort(null);
        for (ExcelHeader header : headers) {
            header.deepSort();
        }
        return headers;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ExcelHeader header = (ExcelHeader) o;
        return row == header.row && column == header.column && Objects.equals(name, header.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, row, column);
    }
}
